import axios from "axios";
import Cookie from "js-cookie";

const debug = process.env.NODE_ENV !== "production";

let BASE_URL = "";

if (debug) {
  BASE_URL = "//angelpool.jinleyuanmall.cn/";
} else {
  BASE_URL = "//angel.jinleyuanmall.cn/";
}

const api_token = Cookie.get("api_token");

export function getBaseUrl() {
  return BASE_URL;
}

export function getPhone() {
    let ret = [];
    let phone = getCookie('user_phone');
    phone && ret.push(phone);
    return ret;
}

export function setCookie(name, value) {
  Cookie.set(name, value);
}

export function removeCookie(name) {
  Cookie.remove(name);
}

export function getCookie(name) {
  return Cookie.get(name);
}

export function getAjax(url, options, needlogin = true) {
  let api_token = getCookie("api_token");
  if (api_token || !needlogin) {
    let base_url = BASE_URL + url;
    let opt = { api_token, ...options };
    return axios.get(base_url, { params: opt }).then(res => {
      return Promise.resolve(res.data);
    });
  } else {
    return Promise.reject({ code: 0, msg: "用户未登录" });
  }
}

export function postAjax(url, options, needlogin = true) {
  let api_token = getCookie("api_token");
  if (api_token || !needlogin) {
    let base_url = BASE_URL + url;
    let opt = { api_token, ...options };
    return axios.post(base_url, opt).then(res => {
      return Promise.resolve(res.data);
    });
  } else {
    return Promise.reject({ code: 0, msg: "用户未登录" });
  }
}

export function checkLogin(needToast = true, fn) {
  let api_token = Cookie.get("api_token");
  let me = this;
  if (needToast && !api_token) {
    let layerIndex = layer.open({
      content: "您还没有登录！",
      btn: "去登陆",
      shadeClose: false,
      yes: function() {
        if (typeof fn === "function") {
          layer.close(layerIndex);
          fn();
        }
      }
    });
    return false;
  }
  if (!needToast && !api_token) {
    return false;
  }
  return true;
}
